<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="员工编码" prop="code">
        <el-input
          v-model.trim="queryParams.code"
          style="width: 200px"
          placeholder="请输入员工编码"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model.trim="queryParams.name"
          style="width: 200px"
          placeholder="请输入姓名"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="在职状态" prop="joinPositionStatus">
        <el-select
          style="width: 200px"
          @change="handleQuery"
          v-model="queryParams.joinPositionStatus"
          placeholder="请选择在职状态"
        >
          <el-option
            v-for="item in mes_user_position_status"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话" prop="telephone">
        <el-input
          v-model.trim="queryParams.telephone"
          style="width: 200px"
          placeholder="请输入联系电话"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input
          v-model.trim="queryParams.idCard"
          style="width: 200px"
          placeholder="请输入身份证号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Upload" @click="handleImport"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Download" @click="handleExport">
          导出
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>
    <div>
      <el-table v-loading="loading" border :data="dataList">
        <el-table-column label="序号" width="60" type="index" align="center" />
        <el-table-column
          label="在职状态"
          width="100"
          align="center"
          :show-overflow-tooltip="true"
          prop="joinPositionStatus"
          v-if="columns[0].visible"
        >
          <template v-slot="{ row }">
            <el-tag
              effect="dark"
              :type="
                row.joinPositionStatus == 3
                  ? 'danger'
                  : row.joinPositionStatus == 2
                  ? 'warning'
                  : ''
              "
            >
              {{ getStatus(row.joinPositionStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="员工编号"
          min-width="160"
          align="center"
          :show-overflow-tooltip="true"
          prop="code"
          v-if="columns[1].visible"
        >
          <template v-slot="{ row }">
            <el-button type="primary" @click="handleView(row)" link>
              {{ row.code }}
            </el-button>
          </template>
        </el-table-column>

        <el-table-column
          label="姓名"
          align="center"
          :show-overflow-tooltip="true"
          prop="name"
          v-if="columns[2].visible"
        ></el-table-column>
        <el-table-column
          label="民族"
          align="center"
          :show-overflow-tooltip="true"
          prop="nation"
          v-if="columns[3].visible"
        >
          <template v-slot="{ row }">
            {{ getNation(row.nation) }}
          </template>
        </el-table-column>

        <el-table-column
            label="所属车间"
            min-width="100"
            align="center"
            :show-overflow-tooltip="true"
            prop="deptOne"
            v-if="columns[12].visible"
        >
          <template v-slot="{ row }">
            {{ getshworkshop(row.shworkshop) }}
          </template>
        </el-table-column>

        <el-table-column
          label="性别"
          align="center"
          :show-overflow-tooltip="true"
          prop="sex"
          v-if="columns[4].visible"
        >
          <template v-slot="{ row }">
            {{ row.sex == 1 ? "男" : "女" }}
          </template>
        </el-table-column>
        <el-table-column
          label="出生日期"
          width="100"
          align="center"
          :show-overflow-tooltip="true"
          prop="birthTime"
          v-if="columns[5].visible"
        >
          <template v-slot="{ row }">
            {{ row.birthTime.split("T")[0] }}
          </template>
        </el-table-column>
        <el-table-column
          label="政治面貌"
          min-width="120"
          align="center"
          :show-overflow-tooltip="true"
          prop="political"
          v-if="columns[6].visible"
        >
          <template v-slot="{ row }">
            {{ getPolitical(row.political) }}
          </template>
        </el-table-column>
        <el-table-column
          label="籍贯"
          min-width="100"
          align="center"
          :show-overflow-tooltip="true"
          prop="nativePlace"
          v-if="columns[7].visible"
        ></el-table-column>
        <el-table-column
          label="联系电话"
          width="150"
          align="center"
          :show-overflow-tooltip="true"
          prop="telephone"
          v-if="columns[8].visible"
        ></el-table-column>
        <el-table-column
          label="最高学历"
          min-width="100"
          align="center"
          :show-overflow-tooltip="true"
          prop="maxXl"
          v-if="columns[9].visible"
        >
          <template v-slot="{ row }">
            {{ getMaxXl(row.maxXl) }}
          </template>
        </el-table-column>
        <el-table-column
          label="毕业院校"
          min-width="100"
          align="center"
          :show-overflow-tooltip="true"
          prop="graduationSchool"
          v-if="columns[10].visible"
        ></el-table-column>
        <el-table-column
          label="所学专业"
          min-width="100"
          align="center"
          :show-overflow-tooltip="true"
          prop="profession"
          v-if="columns[11].visible"
        ></el-table-column>

        <el-table-column
          label="二级部门"
          min-width="100"
          align="center"
          :show-overflow-tooltip="true"
          prop="deptTwo"
          v-if="columns[13].visible"
        ></el-table-column>
        <el-table-column
          label="入职日期"
          width="100"
          align="center"
          :show-overflow-tooltip="true"
          prop="joinTime"
          v-if="columns[14].visible"
        >
          <template v-slot="{ row }">
            {{ row.joinTime.split("T")[0] }}
          </template>
        </el-table-column>
        <el-table-column
          label="在职岗位"
          min-width="100"
          align="center"
          :show-overflow-tooltip="true"
          prop="joinPositionPost"
          v-if="columns[15].visible"
        ></el-table-column>
        <el-table-column
          label="照片"
          align="center"
          :show-overflow-tooltip="true"
          prop="address"
          v-if="columns[16].visible"
        >
          <template v-slot="{ row }">
            <div class="demo-image__preview" v-if="row.photo">
              <el-image
                style="width: 40px; height: 40px"
                :src="row.photo"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[row.photo]"
                preview-teleported
                fit="cover"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="150"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-button link type="primary" @click="handleStatus(scope.row)">
              {{ scope.row.joinPositionStatus == 3 ? "复职" : "离职" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />
              是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
            >
              下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="personnel">
import { downLoad } from "@/utils/ruoyi";
import { onActivated, ref } from "vue";
import {
  getMesUserInfo,
  delMesUserInfo,
  editMesUserInfo,
  exportTemplate,
  exportMesUserInfo,
} from "@/api/basicInfo/personnel";
const { proxy } = getCurrentInstance();
const loading = ref(true);
const dataList = ref([]);
const showSearch = ref(true);
const total = ref(0);
const router = useRouter();
import { getToken } from "@/utils/auth";
import { ElMessage } from "element-plus";
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/mes/user/importMesUserInfo",
});
// 列显隐信息
const columns = ref([
  { key: 0, label: `在职状态`, visible: true },
  { key: 1, label: `员工编号`, visible: true },
  { key: 2, label: `姓名`, visible: true },
  { key: 3, label: `民族`, visible: true },
  { key: 4, label: `性别`, visible: true },
  { key: 5, label: `出生日期`, visible: true },
  { key: 6, label: `政治面貌`, visible: true },
  { key: 7, label: `籍贯`, visible: true },
  { key: 8, label: `联系电话`, visible: true },
  { key: 9, label: `最高学历`, visible: true },
  { key: 10, label: `毕业院校`, visible: true },
  { key: 11, label: `所学专业`, visible: true },
  { key: 12, label: `一级部门`, visible: true },
  { key: 13, label: `二级部门`, visible: true },
  { key: 14, label: `入职日期`, visible: true },
  { key: 15, label: `在职状态`, visible: true },
  { key: 16, label: `照片`, visible: true },
]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    code: undefined,
    status: undefined,
    joinPositionStatus: "1",
    telephone: undefined,
    idCard: undefined,
  },
});
const { queryParams } = toRefs(data);
const {
  mes_user_nation,
  mes_user_position_status,
  mes_user_political,
  mes_user_max_xl,
  sh_workshop
} = proxy.useDict(
  "mes_user_nation",
  "mes_user_position_status",
  "mes_user_political",
  "mes_user_max_xl",
    "sh_workshop"
);
const getStatus = (row) => {
  const val = mes_user_position_status.value.find((item) => item.value == row);
  return val ? val.label : "";
};
const getNation = (row) => {
  const val = mes_user_nation.value.find((item) => item.value == row);
  return val ? val.label : "";
};

const getshworkshop = (row) => {
  const val = sh_workshop.value.find((item) => item.value == row);
  return val ? val.label : "";
};

const getPolitical = (row) => {
  const val = mes_user_political.value.find((item) => item.value == row);
  return val ? val.label : "";
};
const getMaxXl = (row) => {
  const val = mes_user_max_xl.value.find((item) => item.value == row);
  return val ? val.label : "";
};
const getList = () => {
  loading.value = true;
  getMesUserInfo(queryParams.value)
    .then((res) => {
      loading.value = false;
      res.rows.forEach((item) => {
        item.photo = item.photo
          ? import.meta.env.VITE_APP_BASE_API + item.photo
          : "";
      });
      dataList.value = res.rows;
      total.value = res.total;
    })
    .catch((err) => {
      loading.value = false;
    });
};
// 新增
const handleAdd = () => {
  router.push("/basicInfo/personnel/details");
};
// 编辑
const handleUpdate = (row) => {
  router.push({
    path: "/basicInfo/personnel/details",
    query: {
      id: row.id,
    },
  });
};
// 查看
const handleView = (row) => {
  router.push({
    path: "/basicInfo/personnel/details",
    query: {
      id: row.id,
      info: true,
    },
  });
};
// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryRef");
  handleQuery();
};
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除"' + row.name + '"的数据项？')
    .then(function () {
      return delMesUserInfo({ id: row.id });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
// 导出
const handleExport = () => {
  exportMesUserInfo(queryParams.value).then((res) => {
    downLoad(res.msg, "人员列表");
  });
};
/** 导入按钮操作 */
function handleImport() {
  upload.title = "员工导入";
  upload.open = true;
}
/** 下载模板操作 */
function importTemplate() {
  exportTemplate().then((res) => {
    downLoad(res.msg, "人员模版");
  });
}
const beforeAvatarUpload = (rawFile) => {
  console.log(rawFile);
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};
// 离职复职
const handleStatus = (row) => {
  const state = row.joinPositionStatus == 3 ? 1 : 3;
  const stateText = row.joinPositionStatus == 3 ? "复职" : "离职";
  proxy.$modal
    .confirm("是否确认" + row.name + stateText)
    .then(function () {
      return editMesUserInfo({ id: row.id, joinPositionStatus: state });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess(`${stateText}成功`);
    })
    .catch(() => {});
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
getList();
// onActivated(() => {
//     getList()
// })
// router.beforeEach((to, from, next) => {
//     if (to.path == "/basicInfo/personnel") {
//         getList()
//     }
//     next();
// });
</script>

<style lang="scss" scoped>
.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

.demo-image__preview {
  cursor: pointer;
}
</style>
